var app = angular.module('fiveApp.services', []);

app.service('session', [function () {
    return {
        set: function (key, val) {
            var data = angular.copy(val);
            var unhashKey = function (data) {
                if (typeof data == 'object') {
                    for (k in data) {
                        if (data[k] && data[k]['$$hashKey']) {
                            delete data[k]['$$hashKey'];
                        }
                    }
                }
            }
            unhashKey(data);
            sessionStorage.setItem(key, JSON.stringify(data));
        },
        get: function (key) {
            var val = sessionStorage.getItem(key);
            return val ? JSON.parse(val) : null;
        }
    }
}])
app.service('localData', [function () {
    return {
        set: function (key, val) {
            var data = angular.copy(val);
            var unhashKey = function (data) {
                if (typeof data == 'object') {
                    for (k in data) {
                        if (data[k] && data[k]['$$hashKey']) {
                            delete data[k]['$$hashKey'];
                        }
                    }
                }
            }
            unhashKey(data);
            localStorage[key] = JSON.stringify(data);
        },
        get: function (key) {
            var val = localStorage[key];
            return val ? JSON.parse(val) : null;
        }
    }
}])

//保存临时数据共控制器之间使用
app.service('tempDataService', [function () {
    var tempData = [];
    return {
        set: function (key, val) {
            tempData[key] = val;
        },
        get: function (key) {
            return tempData[key] || null;
        }
    };
}]);

app.service('ajaxService', ['$http', function ($http) {
    var sendAjax = function (url, method, params, cb, cb2, loding) {
        method = method.toLocaleUpperCase();
        var body = angular.copy(params);
        var unNullVal = function (arr) {
            for (i in arr) {
                if (arr[i] === null) {
                    arr[i] = '';
                }
                if (typeof (arr[i]) === 'object') {
                    unNullVal(arr[i]);
                }
            }
        };
        unNullVal(body);
        for (var k in body) {
            if (body.hasOwnProperty(k)) {
                if (k.indexOf("$") != -1) {
                    url.replace("{" + k + "}", body[k]);
                    delete body[k];
                }
                if (typeof (body[k]) === 'object') {
                    body[k] = JSON.stringify(body[k]);
                }
            }
        }
        var header = {
            'Accept': '*/*',
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        };

        var layerIndex = 0;
        if (loding) {
            $.iBox.loading();
        }

        var verifyErrCode = function (rel) {
            if (rel.errCode) {
                $.iBox.error(rel.message);
            }
        }
        switch (method) {
            case "GET":
                var config = {params: body, headers: header};
                $http.get(url, config).success(function (rel) {
                    $.iBox.close();
                    verifyErrCode(rel);
                    cb && cb(rel);
                }).error(function (err) {
                    //$.iBox.error(rel.message);
                    cb2 && cb2(err);
                })
                break;
            case "POST":
                var params = '';
                for (i in body) {
                    params += i + "=" + body[i] + "&";
                }
                params = params.substr(0, params.length - 1);
                $http.post(url, params, {headers: header}).success(function (rel) {
                    $.iBox.close();
                    verifyErrCode(rel);
                    cb && cb(rel);
                }).error(function (err) {
                    //$.iBox.error(rel.message);
                    cb2 && cb2(err);
                })
                break;
        }
    }
    var service = function (method, opts, cb, cb2, hideLoding) {
        if (typeof cb2 == 'boolean') {
            hideLoding = cb2;
        }
        var loding = hideLoding ? false : true;
        if (typeof (method) === "object") {
            mm = method
        } else {
            mm = window._AppConfig.AjaxApi[method];
        }

        if (mm) {
            sendAjax(mm.url, mm.method, opts, cb, cb2, loding);
        } else {
            //未找到方法
            console.log("url 错误", "返回结果：err = ", "无法请求，无效的请求！", "\n");
            $.iBox.error('无效的请求' + method);
            cb2 && cb2({errCode: -1, message: "无效的请求"})
        }
    }
    return service;
}])